package com.yunmai.cloud.web.utils;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author WangChen
 * @since 2021-01-07
 */
public class JacksonUtils {

    private static final Logger logger = LoggerFactory.getLogger(JacksonUtils.class);

    /**
     * 线程安全滴 公用一个会降低效率 怎么取舍
     */
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();


    public static String toJsonString(Object object){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            logger.error(ExceptionUtil.stacktraceToString(e));
        }
        return null;
    }

    public static byte[] toJsonByte(Object object){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsBytes(object);
        } catch (JsonProcessingException e) {
            logger.error(ExceptionUtil.stacktraceToString(e));
        }
        return null;
    }

    public static <T> T parseObject(String string, Class<T> clazz){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(string, clazz);
        } catch (JsonProcessingException e) {
            logger.error(ExceptionUtil.stacktraceToString(e));
        }
        return null;
    }
}
